<template>
  <el-dialog
    :title="title"
    :visible="visible"
    width="700px"
    :before-close="closeForm"
    :close-on-click-modal="false"
  >
    <el-form
      ref="pageEdit"
      label-width="120px"
    >
      <el-form-item v-for="row in rows" :key="row.Value" :label="row.Text">
        <el-input
          v-model="row.Path"
          maxlength="255"
          placeholder="页面路径"
        >
          <template slot="append">
            <el-button type="primary" icon="el-icon-check" @click="save(row)" />
            <el-button type="warning" icon="el-icon-refresh" @click="resetForm(row)" />
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import * as pageApi from '@/customForm/api/phyPage'
import { GetItems } from '@/api/base/enumDic'
export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      rows: [],
      pageType: null,
      source: null,
      title: '编辑表单页面路径'
    }
  },
  computed: {
    comId() {
      return this.$store.getters.curComId
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.initPageType()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    async initPageType() {
      this.pageType = await GetItems('PyFormPageType', 'form')
      this.reset()
    },
    resetForm(row) {
      const path = this.source.find(a => a.PageType === row.Value)
      row.Path = path == null ? null : path.PagePath
    },
    async reset() {
      if (this.pageType == null) {
        this.initPageType()
        return
      }
      const list = await pageApi.Gets(this.formId)
      this.source = list
      this.rows = this.pageType.map(c => {
        const path = list.find(a => a.PageType === c.Value)
        return {
          Text: c.Text,
          Value: c.Value,
          Path: path == null ? null : path.PagePath
        }
      })
    },
    async save(row) {
      await pageApi.Set({
        FormId: this.formId,
        PageType: row.Value,
        PagePath: row.Path
      })
      const path = this.source.find(a => a.PageType === row.Value)
      if (path == null) {
        this.source.push({
          PageType: row.Value,
          PagePath: row.Path
        })
      } else {
        path.PagePath = row.Path
      }
      this.$message({
        message: '更新成功!',
        type: 'success'
      })
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close')
    }
  }
}
</script>
